<template>
  <div>
    <a-spin :spinning="confirmLoading" style="background: #fff">
      <j-form-container :disabled="false">
        <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
          <a-collapse v-model="activeKey">
            <!-- 基本信息 -->
            <a-collapse-panel key="1" header="基本信息">
              <a-row :gutter="48">
                <a-col :span="8" :hidden="true">
                  <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                    <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                    <a-input :disabled="formDisabled" v-model="model.billNo" placeholder="请输入单据编号"  disabled></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                    <j-date :disabled="formDisabled" placeholder="请选择申请时间" v-model="model.createTime" :show-time="true"
                            date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                    <select-user-by-dep
                      placeholder="请选择申请人"
                      :disabled="formDisabled"
                      v-model="model.proposer" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                    <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.proposerDeptId" disabled/>
                  </a-form-model-item>
                </a-col>
                <!--迭代11 财务优化 在单据中新增“申请公司”字段，为了审批找到对应的审批人，放在申请部门后-->
                <a-col :span="8">
                  <a-form-model-item label="申请公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyCompany">
                    <select-Company-input :disabled="formDisabled" v-model="model.applyCompany" @back="companyBack"/>
                  </a-form-model-item>
                </a-col>
                <!--迭代11 财务优化 在单据中新增“所属团队”字段-->
                <a-col :span="8">
                  <a-form-model-item label="所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                    <select-team-input
                      :disabled="formDisabled"
                      placeholder="请选择申请人所属团队"
                      v-model="model.teamId"
                      :tdlx="3"
                      @back="teamBack"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="model.teamYear=='2023'">
                  <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamYear">
                    <j-dict-select-tag
                      type="list"
                      v-model="model.teamYear"
                      dictCode="tdnd_type"
                      placeholder="请选择费用所属年度"
                      disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                    <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
            <!-- 还款明细 -->
            <a-collapse-panel key="2" header="还款明细">
              <a-row :gutter="48">
                <erp-finance-repayment-slip-detail-list ref="slipDetailList" @slipDetailData="slipDetailData" :teamId="model.teamId" :applyCompany="model.applyCompany" :disabled="formDisabled"></erp-finance-repayment-slip-detail-list>
              </a-row>
            </a-collapse-panel>
            <!-- 附件信息 -->
            <a-collapse-panel key="3" header="附件信息">
              <a-row :gutter="48">
                <a-col :span="24">
                  <a-form-model-item prop="attachments">
                    <j-upload :disabled="formDisabled" v-model="model.attachments"></j-upload>
                    <!-- <a-button v-else icon="download" @click="viewFile(model.attachments)">文件列表</a-button> -->
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </a-form-model>
        <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
        <view-file-modal ref="viewFileModal"></view-file-modal>
      </j-form-container>
      <a-row :gutter="48" v-if="formBpm">
        <a-col :span="24" style="text-align: center;margin-top: 15px">
          <a-button type="primary" @click="onPrint">打印</a-button>
        </a-col>
      </a-row>
      <erp-finance-repayment-slip-form-print v-if="formBpm" class="print_style" id="repaymentContent" :formData="model" :formDataHistory="formData"></erp-finance-repayment-slip-form-print>
    </a-spin>
  </div>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import ErpFinanceRepaymentSlipDetailList from './reference/ErpFinanceRepaymentSlipDetailList';
import ErpFinanceRepaymentSlipFormPrint from './ErpFinanceRepaymentSlipFormPrint'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput';
import SelectTeamInput from '@/views/scy/components/SelectTeamInput';
import {Decimal} from "decimal.js";
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import {  initDictOptions,filterMultiDictText } from '@/components/dict/JDictSelectUtil'

  export default {
    name: 'ErpFinanceRepaymentSlipForm',
    mixins: [viewFile],
    components: {
      ViewFileModal,
      SelectUserByDep,
      ErpFinanceRepaymentSlipDetailList,
      SelectCompanyInput,
      SelectTeamInput,
      CommonFlowList,
      ErpFinanceRepaymentSlipFormPrint
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      //迭代11 还款单改为审批
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      // 是否详情
      detail: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        activeKey: ['1','2','3'],
        model:{
          billNo: null,
          checkStatus: 0,
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          applyCompany: [
            { required: true, message: '请选择申请公司!'},
          ],
          teamId: [
            { required: true, message: '请选择所属团队!'},
          ]
        },
        url: {
          add: "/api/erp/finance/repayment/erpFinanceRepaymentSlip/add",
          edit: "/api/erp/finance/repayment/erpFinanceRepaymentSlip/edit",
          queryById: "/api/erp/finance/repayment/erpFinanceRepaymentSlip/queryById",
          gainBillNo: "/api/erp/finance/repayment/erpFinanceRepaymentSlip/gainBillNo"
        },
        userName: '',
        companyIdBackups: null,
        teamIdBackups: null,
        detailData: [],
        dictOptions:[],
      }
    },
    computed: {
      // formDisabled(){
      //   return this.disabled
      // },
      // 迭代11 还款单改为审批
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      // 字典
      this.initDicts()
    },
    methods: {
      ...mapGetters(['userInfo']),
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            that.model.billNo = res.result//单据编号
            that.model.bpmBizTitle = that.userName + '-' + that.model.billNo//标题
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;//当前登录人名称
        this.model.proposer = this.userInfo().empId; //当前登录人
        this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.getBillNo() //获取单据编号
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        if(this.model.id) {
          this.$refs.slipDetailList.loadData(1, this.model.id)
        } else {
          this.$refs.slipDetailList.dataSource = []
        }
        if (!!this.model.teamId) {
          this.teamIdBackups = this.model.teamId
        }
        if (!!this.model.applyCompany) {
          this.companyIdBackups = this.model.applyCompany
        }
        this.visible = true;
      },
      slipDetailData(data) {
        this.detailData = data
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let slipDetailList = this.$refs.slipDetailList.submitForm()
          if (!slipDetailList.length > 0) {
            this.$message.warning('请添加还款单信息！');
            this.$emit('unButtonDisable');
            return
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        let slipDetailList = this.$refs.slipDetailList.submitForm() || []
        let teamName = filterMultiDictText(this.dictOptions['teamManager'], that.model.teamId + '')
        let createTime = this.getCreateTime()
        let currentReturnAmount = 0
        let dataSource = that.$refs.slipDetailList.dataSource || []
        for (const item of dataSource) {
          currentReturnAmount = currentReturnAmount + item.currentReturnAmount
        }
        // 迭代16.7 取费用所属团队-申请人-申请日期（年月日）-金额（取报销明细费用累计）
        that.model.bpmBizTitle = (that.model.teamId ? teamName + '-' : '') + that.userInfo().empName + ' - ' + createTime + (currentReturnAmount ? '-' + currentReturnAmount : '') // 标题
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.slipDetailList = slipDetailList
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      teamBack(item) {
        //判断不为空
        if(!!this.model.teamId && item.length > 0) {
          //判断团队是否变化
          if(this.teamIdBackups !== item[0].id) {
            if(this.detailData.length > 0) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换所属团队，此操作将会清空还款明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.teamIdBackups = that.model.teamId
                  //清空子表数据
                  that.$refs.slipDetailList.dataSource = []
                  that.detailData = []
                  that.model.teamYear = item[0].tdnd;
                },
                onCancel() {
                  that.model.teamId = that.teamIdBackups
                }
              });
            } else {
              this.teamIdBackups = item[0].id
              this.model.teamYear = item[0].tdnd;
            }
          }
        }
      },
      companyBack(item) {
        //判断不为空
        if(!!this.model.applyCompany && item.length > 0) {
          //判断公司是否变化
          if(this.companyIdBackups !== item[0].id) {
            if(this.detailData.length > 0) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换申请公司，此操作将会清空还款明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.companyIdBackups = that.model.applyCompany
                  //清空子表数据
                  that.$refs.slipDetailList.dataSource = []
                  that.detailData = []
                },
                onCancel() {
                  that.model.applyCompany = that.companyIdBackups
                }
              });
            } else {
              this.companyIdBackups = item[0].id
            }
          }
        }
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#repaymentContent',
          popTitle: '还款申请详情 · 禾美环保',
          endCallback() {

          }
        })
      },
      initDicts(){
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamManager', res.result)
          }
        })
      },
      getCreateTime() {
        let createTime = this.model.createTime;
        console.log(createTime)
        let date = createTime.substring(0,10)
        return date.substring(0,4) +'年'+ date.substring(5,7)+'月' + date.substring(8,10)+'日';
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>